//
//  YAYIShareView.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/6.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIShareView.h"

#import "UMSocialQQHandler.h"
#import "UMSocialSinaSSOHandler.h"
#import "UMSocial.h"

@interface YAYIShareView()

//@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UIView *actionSheet;


@end


@implementation YAYIShareView


//- (instancetype)initWithFrame:(CGRect)frame
//{
//    if (self == [super initWithFrame:frame]) {
//        [self setupSubView];
//    }
//    return self;
//}


- (instancetype)initWithDelegate:(id)delegate
{
    if (self = [super init]) {
        [self setupSubView];
    }
    return self;
}


- (void)setupSubView
{
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    
//    self.backgroundColor = [UIColor clearColor];
//    self.backgroundView = [UIView new];
//    self.backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
//    [self addSubview:self.backgroundView];
    
    // 遮盖
    UIView *coverView = [[UIView alloc] init];
    coverView.backgroundColor = [UIColor clearColor];
    [coverView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(maskViewClick:)]];
    [self addSubview:coverView];
    self.coverView = coverView;

    
    // 底部弹窗
    UIView *actionSheet = [[UIView alloc] init];
    actionSheet.backgroundColor = [UIColor whiteColor];
    [coverView addSubview:actionSheet];
    self.actionSheet = actionSheet;
    
    
    // 添加标题
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"分享到";
    titleLbl.font = [UIFont systemFontOfSize:15];
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [actionSheet addSubview:titleLbl];
    
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@10);
        make.left.right.equalTo(actionSheet);
    }];
    
    // 创建按钮
    NSInteger shareBtnCount = 4;
    CGFloat shareBtnY = 60 * YAYIScreenScale;
    CGFloat shareBtnWH = 57 * YAYIScreenScale;
    CGFloat shareMargin = (SCREEN_width - shareBtnCount * shareBtnWH) / (shareBtnCount + 1);
    for (int i = 0; i < shareBtnCount; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        btn.backgroundColor = [UIColor blueColor];
        
        NSString *imgStr = [NSString stringWithFormat:@"share%d", i + 1];
        [btn setImage:[UIImage imageNamed:imgStr] forState:UIControlStateNormal];
        btn.tag = i;
        [btn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [actionSheet addSubview:btn];
        
        CGFloat shareBtnX = (shareBtnWH + shareMargin) * i + shareMargin;
        btn.frame = CGRectMake(shareBtnX, shareBtnY, shareBtnWH, shareBtnWH);
        
    }
    
    // 添加取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"register_button_normal"] forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [actionSheet addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(cancelClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(actionSheet).offset(30);
        make.right.equalTo(actionSheet).offset(-30);
        make.height.equalTo(@(40 * YAYIScreenScale));
        make.top.equalTo(@(155 * YAYIScreenScale));
    }];
}


- (void)show
{
    if (self.superview != nil) return;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    self.frame = keyWindow.bounds;
    [keyWindow addSubview:self];
    
    
//    self.backgroundView.frame = CGRectMake(0, 0, SCREEN_width, SCREEN_height);
    self.coverView.frame = self.bounds;
    

    self.actionSheet.frame = CGRectMake(0, SCREEN_height, SCREEN_width, 220 * YAYIScreenScale);
    
    
    // 动画显示
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        self.actionSheet.y = self.height - self.actionSheet.height;
    }];
}


#pragma mark - 点击事件
/**
 *  分享按钮点击
 */
-(void)shareBtnClick:(UIButton *)btn
{
    UIImage *shareIcon = [UIImage imageNamed:@"icon"];
    if (self.shareImage) {
        shareIcon = self.shareImage;
    }
    
    UMSocialUrlResource *resource = nil;
    if (self.urlStr) {
        resource = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeWeb url:self.urlStr];
    }
    
    NSString *shareContent = @"雅同医生版";
    if (self.shareContent) {
        shareContent = self.shareContent;
    }
    
    NSString *shareType = nil;
    UIViewController *ctl = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    // 分享暂时隐藏掉
    if (0 == btn.tag) { // 微信分享
        
        shareType = UMShareToWechatSession;
    }else if (1 == btn.tag){ // 朋友圈分享
        
        shareType = UMShareToWechatTimeline;
    }else if (2 == btn.tag){ // qq分享
        
        shareType = UMShareToQQ;
    }else if (3 == btn.tag){ // 新浪分享
        
        shareType = UMShareToSina;
    };
    
    
    if (shareType == UMShareToQQ ) {
        
        resource = nil;
        [UMSocialQQHandler setQQWithAppId:VRQQAppID appKey:VRQQAppSecret url:self.urlStr];
    }else if (shareType == UMShareToSina){
        NSString *shareTitle = [self.shareTitle stringByReplacingOccurrencesOfString:@"[" withString:@""];
        shareTitle = [shareTitle stringByReplacingOccurrencesOfString:@"]" withString:@""];
        shareContent = [NSString stringWithFormat:@"【%@】  %@ %@",shareTitle, shareContent, self.urlStr];
        resource = nil;
    }else{
        
        
    }
    
    
    [UMSocialData defaultData].extConfig.title = self.shareTitle;
    [UMSocialData defaultData].extConfig.qqData.url = self.urlStr;
    
     [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:self.imageUrlStr] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
         
     } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
         
         if (error) {
             
             UIImage *defaultImage = [UIImage imageNamed:@"default"];
             [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[shareType] content:shareContent image:defaultImage location:nil urlResource:resource presentedController:ctl completion:^(UMSocialResponseEntity *response){
                 if (response.responseCode == UMSResponseCodeSuccess) {
                     NSLog(@"分享成功！");
                 }
             }];
         }else{
             
             [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[shareType] content:shareContent image:image location:nil urlResource:resource presentedController:ctl completion:^(UMSocialResponseEntity *response){
                 if (response.responseCode == UMSResponseCodeSuccess) {
                     NSLog(@"分享成功！");
                 }
             }];
         }
     }];
}


- (void)cancelClick:(UIButton *)sender
{
    
    [self dismiss];
}

- (void)maskViewClick:(UITapGestureRecognizer *)sender
{
    [self dismiss];
    
}


- (void)dismiss{
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        self.actionSheet.y = self.height;
    } completion:^(BOOL finished) {
        if (self.superview != nil) {
            [self removeFromSuperview];
        }
    }];
}


@end
